<template>
    <div class="user-container">
        <el-card shadow="never">
            <el-form @submit.prevent inline class="search-form">
                <el-form-item label="用户名" size="default">
                    <el-input
                        v-model="username"
                        placeholder="请输入用户名"
                        size="default"
                        @keyup.enter="handleQuery"
                    ></el-input>
                </el-form-item>
                <el-form-item size="default">
                    <el-button
                        type="primary"
                        @click="handleRemoveUsernameQuery"
                    >
                        重置
                    </el-button>
                    <el-button
                        icon="Search"
                        type="primary"
                        :disabled="!username"
                        @click="handleQuery"
                    >
                        搜索
                    </el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card shadow="never">
            <el-button
                icon="Plus"
                type="primary"
                size="default"
                @click="addUser"
            >
                添加用户
            </el-button>
            <el-button
                icon="Delete"
                type="danger"
                size="default"
                :disabled="selectArr.length === 0"
                @click="handleDeleteUsers"
            >
                批量删除
            </el-button>
            <el-table
                ref="userTable"
                :show-overflow-tooltip="true"
                max-height="430px"
                tooltip-effect="dark"
                :data="tableData"
                border
                stripe
                style="margin-top: 10px"
                @selection-change="handleSelectionChange"
            >
                <el-table-column width="50" type="selection"></el-table-column>
                <el-table-column width="80" label="序号">
                    <template #default="{ $index }">
                        {{ $index + 1 }}
                    </template>
                </el-table-column>
                <el-table-column
                    width="150"
                    label="用户名"
                    prop="username"
                ></el-table-column>
                <el-table-column
                    width="150"
                    label="昵称"
                    prop="nickName"
                ></el-table-column>
                <el-table-column width="200" label="角色">
                    <template #default="{ row }">
                        <template v-if="row.roles">
                            <el-tag
                                v-for="(r, index) in row.roles.split(',')"
                                :key="index"
                                type="success"
                                style="margin-right: 2px"
                            >
                                {{ r }}
                            </el-tag>
                        </template>
                        <el-tag v-else type="info">无</el-tag>
                    </template>
                </el-table-column>
                <el-table-column width="80" label="状态">
                    <template #default="{ row }">
                        <el-tag :type="row.status === 1 ? 'primary' : 'danger'">
                            {{ row.status === 1 ? '启用' : '禁用' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column
                    width="180"
                    label="创建时间"
                    prop="createTime"
                ></el-table-column>
                <el-table-column label="操作">
                    <template #default="{ row }">
                        <el-button
                            icon="User"
                            type="primary"
                            size="small"
                            @click="assignRoleButton(row.id)"
                        >
                            分配角色
                        </el-button>
                        <el-button
                            icon="Edit"
                            type="warning"
                            size="small"
                            @click="editUser(row.id)"
                        >
                            编辑
                        </el-button>
                        <el-popconfirm
                            width="200"
                            title="你确定要删除这一项吗?"
                            @confirm="handleRemoveUser(row.id)"
                        >
                            <template #reference>
                                <el-button
                                    icon="Delete"
                                    type="danger"
                                    size="small"
                                >
                                    删除
                                </el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <el-pagination
            v-model:current-page="current"
            v-model:page-size="pageSize"
            :page-sizes="[10, 15, 20, 25]"
            small
            layout=" prev, pager, next, jumper,->,sizes, total"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
        <el-dialog
            v-model="dialogVisible"
            :title="dialogTitle"
            width="700"
            @open="getRoles"
        >
            <el-form
                ref="actionForm"
                :model="userItem"
                label-position="right"
                :rules="rules"
                label-width="80"
                inline
            >
                <el-form-item v-show="false" prop="id"></el-form-item>
                <el-form-item label="用户名" prop="username">
                    <el-input
                        :disabled="actionType === TYPE.EDIT"
                        v-model="userItem.username"
                    ></el-input>
                </el-form-item>
                <el-form-item label="昵称" prop="nickName">
                    <el-input v-model="userItem.nickName"></el-input>
                </el-form-item>
                <el-form-item label="角色" prop="roles">
                    <el-select
                        multiple
                        v-model="userItem.roles"
                        placeholder="请选择角色"
                        style="width: 190px"
                    >
                        <el-option
                            v-for="r in roles"
                            :key="r.id"
                            :label="r.remark"
                            :value="r.id"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item
                    v-show="actionType === TYPE.ADD"
                    label="密码"
                    prop="password"
                >
                    <el-input
                        show-password
                        v-model="userItem.password"
                    ></el-input>
                </el-form-item>
                <el-form-item label="密码" v-show="actionType === TYPE.EDIT">
                    <el-tooltip content="密码重置为123456" placement="right">
                        <el-button type="primary" @click="resetPwd()">
                            重置密码
                        </el-button>
                    </el-tooltip>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-select
                        v-model="userItem.status"
                        placeholder="请选择状态"
                        style="width: 190px"
                    >
                        <el-option label="启用" :value="1"></el-option>
                        <el-option label="禁用" :value="0"></el-option>
                    </el-select>
                </el-form-item>
                <el-col :span="24">
                    <el-form-item label="头像" prop="avatar">
                        <el-upload
                            class="avatar-uploader"
                            action="#"
                            ref="upload"
                            :auto-upload="true"
                            :http-request="handleFileUpload"
                            :show-file-list="false"
                        >
                            <img
                                v-if="userItem.avatar"
                                :src="userItem.avatar"
                                class="avatar"
                            />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-form-item>
                </el-col>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="closeDialog">取消</el-button>
                    <el-button type="primary" @click="handleSaveOrUpdate">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <el-drawer
            v-model="drawerVisible"
            title="分配角色"
            direction="rtl"
            size="400"
            @open="openDrawer"
        >
            <el-form ref="assignRoleForm" :model="assignRoleItem">
                <el-col :span="20" :push="2">
                    <el-form-item label="用户名" prop="currentUsername">
                        <el-input
                            v-model="assignRoleItem.currentUsername"
                            disabled
                        ></el-input>
                    </el-form-item>
                    <el-form-item prop="rolesCheck">
                        <el-checkbox-group v-model="assignRoleItem.rolesCheck">
                            <el-checkbox
                                v-for="r in roles"
                                :value="r.id"
                                :label="r.remark"
                                :key="r.id"
                            ></el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                </el-col>
                <div
                    style="
                        text-align: right;
                        padding-right: 30px;
                        margin-top: 20px;
                    "
                >
                    <el-button @click="resetDrawer">取消</el-button>
                    <el-button type="primary" @click="assignRole">
                        确认
                    </el-button>
                </div>
            </el-form>
        </el-drawer>
    </div>
</template>

<script setup lang="ts" name="User">
import { PageInfo } from '@/api/type'
import {
    reqAddUser,
    reqAssignRole,
    reqDeleteUser,
    reqUpdateUser,
    reqUserPage,
    reqUserWithRoles,
    resetPassword,
} from '@/api/authority/user'
import { AssignRole, UserItem, UserPageItem } from '@/api/authority/user/type'
import {
    ElMessage,
    ElTable,
    FormInstance,
    FormRules,
    UploadRequestOptions,
} from 'element-plus'
import { computed, onMounted, reactive, ref } from 'vue'
import { resetForm } from '@/utils/elFromUtil.ts'
import { reqRoles } from '@/api/authority/role'
import { Role } from '@/api/authority/role/type.ts'
import { reqFileUpload } from '@/api/file'

// 重置密码
const resetPwd = () => {
    resetPassword(userItem.id).then(() => {
        ElMessage.success('密码重置成功')
    })
}
let drawerVisible = ref(false)
let assignRoleForm = ref<FormInstance>()
const resetDrawer = () => {
    drawerVisible.value = false
    resetForm(assignRoleForm)
}
const assignRole = () => {
    const dto: AssignRole = {
        userId: assignRoleItem.id,
        roles: assignRoleItem.rolesCheck,
    }
    reqAssignRole(dto).then(() => {
        ElMessage.success('分配角色成功')
        drawerVisible.value = false
        getUserPage()
    })
}

// 用户角色
interface AssignRoleItem {
    currentUsername: string
    rolesCheck: number[]
    id: number
}

let assignRoleItem = reactive<AssignRoleItem>({
    currentUsername: '',
    rolesCheck: [],
    id: 0,
})
const openDrawer = () => {
    reqRoles().then((res) => {
        roles.value = res.data
    })
}
const assignRoleButton = (id: number) => {
    drawerVisible.value = true
    reqUserWithRoles(id).then((res) => {
        assignRoleItem.currentUsername = res.data.username
        assignRoleItem.rolesCheck = res.data.roles.map((i) => i.id)
        assignRoleItem.id = res.data.id
    })
}
const handleFileUpload = (fileObject: UploadRequestOptions) => {
    let fd = new FormData()
    fd.append('file', fileObject.file)
    reqFileUpload(fd)
        .then((res) => {
            userItem.avatar = res.data
        })
        .catch((err) => {
            ElMessage({
                message: err,
                type: 'error',
            })
        })
}
// 定义角色列表
let roles = ref<Role[]>([])
// 获取用户信息和角色信息
const getRoles = () => {
    reqRoles().then((result) => {
        roles.value = result.data
    })
}

//表单校验
interface RuleForm {
    username: string
    password: string
}

const actionForm = ref<FormInstance>()
const rules = reactive<FormRules<RuleForm>>({
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
})

// 模态框数据
enum TYPE {
    EDIT,
    ADD,
}

let userItem = reactive<UserItem>({
    id: 0,
    username: '',
    nickName: '',
    roles: [],
    status: 0,
    avatar: '',
    password: '123456',
})
const closeDialog = () => {
    resetForm(actionForm)
    dialogVisible.value = false
}
const addUser = () => {
    dialogVisible.value = true
    actionType.value = TYPE.ADD
}
const editUser = (id: number) => {
    reqUserWithRoles(id).then((res) => {
        const { id, roles, username, nickName, status, avatar } = res.data
        userItem.id = id
        userItem.roles = roles.map((i) => i.id)
        userItem.nickName = nickName
        userItem.username = username
        userItem.status = status
        userItem.avatar = avatar
    })
    dialogVisible.value = true
    actionType.value = TYPE.EDIT
}
const handleSaveOrUpdate = () => {
    if (actionType.value === TYPE.ADD) {
        actionForm.value?.validate((isValid, invalidFields) => {
            if (isValid) {
                reqAddUser(userItem).then(() => {
                    ElMessage.success('新增成功')
                    dialogVisible.value = false
                    resetForm(actionForm)
                    getUserPage()
                })
            } else {
                console.log('submit error', invalidFields)
            }
        })
    } else {
        reqUpdateUser(userItem).then(() => {
            ElMessage.success('修改成功')
            dialogVisible.value = false
            resetForm(actionForm)
            getUserPage()
        })
    }
}
let actionType = ref()
const dialogTitle = computed(() => {
    return actionType.value === TYPE.EDIT ? '修改用户' : '新增用户'
})
let dialogVisible = ref(false)
let username = ref('')
// 分页
// 分页数据
let pageInfo = reactive<PageInfo>({
    page: 1,
    limit: 10,
})
let userTable = ref<InstanceType<typeof ElTable>>()
let current = ref(1)
let pageSize = ref(10)
let total = ref(0)
let selectArr = ref<number[]>([])

function getUserPage() {
    reqUserPage(pageInfo, username.value)
        .then((res) => {
            tableData.value = res.data.records
            total.value = res.data.total
            current.value = res.data.current
        })
        .catch((err) => {
            console.log(err)
        })
}

const handleRemoveUser = (id: number) => {
    selectArr.value.push(id)
    reqDeleteUser(selectArr.value)
        .then(() => {
            ElMessage({
                message: '删除成功',
                type: 'success',
            })
            selectArr.value = []
            userTable.value?.clearSelection()
            getUserPage()
        })
        .catch(() => {
            selectArr.value = []
            userTable.value?.clearSelection()
        })
}
const handleDeleteUsers = () => {
    const ids = selectArr.value
    reqDeleteUser(ids)
        .then(() => {
            ElMessage({
                message: '删除成功',
                type: 'success',
            })
            selectArr.value = []
            userTable.value?.clearSelection()
            getUserPage()
        })
        .catch(() => {
            selectArr.value = []
            userTable.value?.clearSelection()
        })
}
const handleSelectionChange = (val: UserPageItem[]) => {
    selectArr.value = val.map((i) => i.id)
}
const handleSizeChange = (val: number) => {
    pageInfo.limit = val
    getUserPage()
}
const handleCurrentChange = (val: number) => {
    pageInfo.page = val
    getUserPage()
}
const handleQuery = () => {
    getUserPage()
}
const handleRemoveUsernameQuery = () => {
    username.value = ''
    getUserPage()
}
let tableData = ref<UserPageItem[]>([])
onMounted(() => {
    getUserPage()
})
</script>

<style lang="less" scoped>
.user-container {
    display: flex;
    flex-direction: column;
    gap: 10px;

    .search-form {
        :deep(.el-form-item) {
            margin-bottom: 0;
            margin-right: 10px;
        }
    }

    .avatar-uploader .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
}
</style>
